package nl.depository.pim.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ioc.services.RegistryShutdownListener;

import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.object.ODatabaseObject;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;

public class DataService implements RegistryShutdownListener
{
	private ODatabaseObject db;
	
	public DataService()
	{
		db = new ODatabaseObjectTx("local:/opt/orientdb-1.0rc1-SNAPSHOT/databases/test").open("admin", "admin");
	}
	
	public void registerEntityClass(Class<?> entityClass)
	{
		db.getEntityManager().registerEntityClass(entityClass);
	}
	
	public void registerEntityClasses(String packageName)
	{
		db.getEntityManager().registerEntityClasses(packageName);
	}
	
	public ODatabaseComplex<Object> save(Object o)
	{
		return db.save(o);
	}
	
	public ODatabaseComplex<Object> begin()
	{
		return db.begin();
	}
	
	public ODatabaseComplex<Object> begin(TXTYPE txType)
	{
		return db.begin(txType);
	}

	public ODatabaseComplex<Object> commit()
	{
		return db.commit();
	}
	
	public ODatabaseComplex<Object> rollback()
	{
		return db.rollback();
	}
	
	public List<Object> query(String query, Object... args)
	{
		try
		{
			return db.query(new OSQLSynchQuery<Object>(query), args);
		}
		catch (Throwable e)
		{
			return new ArrayList<Object>();
		}
	}
	
	public Object retrieveRecord(String id) throws Exception
	{
		Object entity = findRecord(id);
		
		if (entity == null)
		{
			throw new Exception("Could not retrieve record " + id);
		}
		
		return entity;
	}
	
	public Object findRecord(String id)
	{
		return query("SELECT FROM " + id).get(0);
	}
	
	public ODatabaseComplex<Object> delete(String id)
	{
		return db.command(new OCommandSQL("DELETE FROM " + id)).execute();
	}
	
	public ODatabaseComplex<Object> delete(Object o)
	{
		return db.delete(o);
	}
	
	public void close()
	{
		if (db != null)
		{
			db.close();
			db = null;
		}
	}
	
	public void registryDidShutdown()
	{
		close();
	}
}
